package org.mm4juser.intercepter;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.SecurityException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.mm4juser.util.JWTTokenUtil;
import org.mm4juser.util.RedisTokenUtil;
import org.springframework.web.servlet.HandlerInterceptor;

public class TokenInterceptor implements HandlerInterceptor {
	@Override public boolean preHandle(
		HttpServletRequest request,
		HttpServletResponse response,
		Object handler) throws Exception {
		String token = request.getHeader("Authorization");
		if (token == null || ! token.startsWith("Bearer ")) {
			response.sendError(
				HttpServletResponse.SC_UNAUTHORIZED,
				"未携带Token");
			return false;
		}
		token = token.substring(7);
		
		try {
			String email = Jwts.parser()
				.verifyWith(JWTTokenUtil.KEY)
				.build()
				.parseClaimsJws(token)
				.getBody()
				.getSubject();
			
			String storedToken = RedisTokenUtil.getToken(email);
			if (storedToken == null || ! storedToken.equals(token)) {
				response.sendError(
					HttpServletResponse.SC_UNAUTHORIZED,
					"Token无效");
				return false;
			}
			request.setAttribute(
				"email",
				email);
			return true;
		}
		catch (ExpiredJwtException |
		       UnsupportedJwtException |
		       MalformedJwtException |
		       SecurityException |
		       IllegalArgumentException e) {
			response.sendError(
				HttpServletResponse.SC_UNAUTHORIZED,
				"Token过期或无效");
			return false;
		}
	}
}
